package ru.cjay.loading {
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;


public class SWFAssetLoader extends EventDispatcher {
    private var _name:String;
    private var _url:String;
    private var _handler:Function;
    private var _swf_asset:SWFAssetList;


//    Флаг наличия процесса загрузки
    private var _progress:int = 0;
    private var _totalBytes:int = 0;
    private var _loadedBytes:int = 0;

    public function SWFAssetLoader() {
    }

//    Вызывается при каждом кадре для подсчёта процента загруженного.
    private function onUpdate(event:ProgressEvent):void {
        var total:int = 0;
        var loaded:int = 0;

        _totalBytes = event.bytesTotal;
        _loadedBytes = event.bytesLoaded;
        _progress = loaded / total;
        event.stopImmediatePropagation();
        dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS, true, true, _totalBytes, _loadedBytes));
    }

    public function loadSWF(item:SWFAssetList):void {

        _url = item.url;
        _name = item.name;

        var RM:ResourceManager = ResourceManager.getInstance();
        if (RM.hasResource(_url)) {
            if (_name) RM.addNameToURL(_url, _name);
            dispatchEvent(new Event(Event.COMPLETE));
            return;
        }
        _swf_asset = item;
        var request:URLRequest = new URLRequest(_url);
        SafeConnection.getInstance().makeSafeLoader(request, onSWFNLoaderComplete, onUpdate);
        return;
    }


    private function onSWFNLoaderComplete(event:Event):void {
        var RM:ResourceManager = ResourceManager.getInstance();

        for (var item:String in _swf_asset.assets) {
            RM.addSwfAsset(_name + ":" + item, event.target.applicationDomain.getDefinition(_swf_asset.get_asset_path(item)) as Class)
        }

        event.stopImmediatePropagation();
        dispatchEvent(new Event(Event.COMPLETE));
    }


    public function get progress():int {
        return _progress;
    }


    public function get totalBytes():int {
        return _totalBytes;
    }

    public function get loadedBytes():int {
        return _loadedBytes;
    }


}
}